#include "DWindow.h"

DWindow*	g_pDWin;
LRESULT CALLBACK WndProc( HWND hWnd
						 , UINT message
						 , WPARAM wParam
						 , LPARAM lParam )
{
	return g_pDWin->WindowProc(hWnd, message, wParam, lParam);
}

DWindow::DWindow(void)
{
	g_pDWin = this;
}

DWindow::~DWindow(void)
{

}

bool DWindow::CreateWin(	HINSTANCE hInstance, 
							const TCHAR* winName /*= _T("DWindowApp") */, 
							int width /*= 800*/, 
							int height /*= 600*/ )
{
	m_hInstance	= hInstance;
	_tcscpy_s(m_winName, MAX_PATH ,winName);
	m_width		= width;
	m_height	= height;

	WNDCLASSEX wcex;

	wcex.cbSize			= sizeof(WNDCLASSEX);
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= m_hInstance;
	wcex.hIcon	= LoadIcon(m_hInstance, IDI_APPLICATION);
	wcex.hIconSm= LoadIcon(m_hInstance, IDI_APPLICATION);
	wcex.hCursor= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)GetStockObject(WHITE_BRUSH);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= m_winName;

	if(!RegisterClassEx(&wcex)) return 0;

	m_hWnd = CreateWindowEx( WS_EX_APPWINDOW
		, m_winName
		, m_winName
		, WS_OVERLAPPEDWINDOW	& ~WS_MAXIMIZEBOX & ~WS_THICKFRAME
		, CW_USEDEFAULT
		, CW_USEDEFAULT
		, m_width
		, m_height
		, NULL
		, NULL
		, m_hInstance
		, NULL );

	if(!m_hWnd)	return false;

	return true;

}

int DWindow::WinRun()
{
	ShowWindow(m_hWnd, SW_SHOW);
	UpdateWindow(m_hWnd);

	MSG			msg = {0};
	while(msg.message != WM_QUIT)
	{
		if(GetMessage(&msg, NULL, 0, 0 ))
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
	}
	return (int)msg.wParam;
}

void DWindow::DestroyWin()
{
	::DestroyWindow(m_hWnd);
}

LRESULT DWindow::WindowProc(	HWND hWnd, 
								UINT message, 
								WPARAM wParam, 
								LPARAM lParam )
{
	switch(message)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hWnd, message, wParam, lParam);
}


